// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, TextInput, Modal, InteractionManager } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import ImagePicker from 'react-native-image-crop-picker';

// antd 按需加载
import { InputItem, Tabs, Toast, Portal, List, Picker } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { region } from '../../module/module.js'

// 引入样式
import Styles from './style.js';

// 引入公用组件
import { Radio, CategoriesGoods } from '../../components/index.js'

// 引入工具包
import { press, size, ScreenWidth, pathHead, ScreenHeight, FileUpload, borderBottom, hotTextColor, validation, defaultDataList, onEndReached, onRefresh, concatDataList, defaultPage } from '../../util/utils.js'

const RenderSelect = (props) => {
	return (
		<TouchableOpacity onPress={props.onPress} style={{
			height: 50,
			padding: 0,
			paddingRight: 15,
			...borderBottom()
		}}>
			<Text style={{ fontSize: 14, color: '#61676F', lineHeight: 50, }}>{props.extra == '请选择' ? props.children : props.extra}</Text>
		</TouchableOpacity>
	)
}

class CardForm extends Component {

	constructor(props) {
		super(props)
		console.log(props.plateList)
		this.state = {
			plateList: props.plateList.map((item) => {
				return {
					value: item.id, label: item.name, children: item.childList.map(itemChildren => {
						return {
							value: itemChildren.id, label: itemChildren.name,
						}
					})
				}
			}),
			plateListId: null,
			visible: false,
			plateListId: [],
			plateId: '',
			goodsList: [],
			imageList: [],
			title: '',
			content: '',
		}
	}


	componentDidMount() {
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.details) {
			this.setState({
				// goodsList,
				// imageList,
				// title,
				// content,
				// plateId: plateListId,
			})
		}
	}

	hanfleOnPress() {
		const { onPress } = this.props
		const { plateListId, goodsList, imageList, title, content } = this.state
		if (!plateListId) {
			Toast.info('请选择板块', 1, null, false);
			return
		}
		if (!title) {
			Toast.info('请输入标题', 1, null, false);
			return
		}
		if (!content) {
			Toast.info('请输入正文', 1, null, false);
			return
		}
		onPress({
			goodsList: goodsList.map(item => item.productId),
			imageList,
			title,
			content,
			plateId: plateListId[1],
		})
	}

	pickGood() {

	}

	pickImages() {
		const { token } = this.props
		let imageList = [...this.state.imageList]
		this.loading = Toast.loading('加载中')
		ImagePicker.openPicker({
			compressImageMaxWidth: 750,
			includeBase64: true,
			loadingLabelText: '处理中',
			mediaType: 'photo',
			cropperToolbarTitle: '选择图片',
			compressImageQuality: .4
		}).then(image => {
			console.log(image)
			// this.setState({
			// 	avatarPic: `data:${image.mime};base64,${image.data}`
			// })
			FileUpload(image).then(res => {

				console.log('上传图片结果', res)
				imageList.push(res.data[0])
				this.setState({
					imageList
				}, () => {
					Portal.remove(this.loading)
				})
				console.log(res, '上传结果')
			}).catch(error => {
				Portal.remove(this.loading)
				Toast.info('上传你失败', 2)
				console.log(error, '上传失败')
			}).finally(() => {
				Portal.remove(this.loading)
			})
		}).catch(e => {
			Portal.remove(this.loading)
		}).finally(() => {
			Portal.remove(this.loading)
		})
	}

	onClose = () => {
		this.setState({
			visible: false
		})
	}

	onSelect = (data) => {
		let goodsList = [...this.state.goodsList]
		let tag = false
		goodsList.map((item, index) => {
			if (item.id == data.id) {
				tag = true
			}
		})
		if (!tag) {
			goodsList.push(data)
			this.setState({
				goodsList
			})
			this.onClose()
		}
	}

	pickGood() {
		this.setState({
			visible: true
		})
	}

	deleteImageListItem(index) {
		let imageList = [...this.state.imageList]
		imageList.splice(index, 1)
		this.setState({
			imageList
		})
	}

	deleteGoodsListItem(index) {
		let goodsList = [...this.state.goodsList]
		goodsList.splice(index, 1)
		this.setState({
			goodsList
		})
	}

	render() {
		const { categoryList } = this.props
		const { visible, plateList, plateListId, goodsList, imageList, title, content } = this.state
		return (
			<ScrollView style={{ flex: 1, paddingBottom: 20 }}>
				<View style={{ paddingLeft: 15 }}>
					<TextInput
						onChangeText={(value) => this.setState({ title: value })}
						placeholder="标题"
						value={title}
						placeholderTextColor="#61676F"
						style={{
							paddingTop: 15,
							paddingBottom: 15,
							color: '#333',
							fontSize: 14,
							...borderBottom()
						}}
						underlineColorAndroid="transparent"
					/>
					<TextInput
						onChangeText={(value) => this.setState({ content: value })}
						placeholder="内容"
						value={content}
						multiline
						numberOfLines={10}
						placeholderTextColor="#61676F"
						style={{
							textAlignVertical: 'top',
							paddingTop: 15,
							paddingBottom: 15,
							color: '#333',
							fontSize: 14,
							...borderBottom()
						}}
						underlineColorAndroid="transparent"
					/>
					<View style={{ flexDirection: 'row', alignItems: 'center' }}>
						<View style={{ flex: 1 }}>
							<Picker
								style={{
								}}
								data={plateList}
								cols={2}
								value={plateListId}
								onChange={(value) => {
									this.setState({
										plateListId: value,
									})
								}}
							>
								<RenderSelect>请选择板块</RenderSelect>
							</Picker>
						</View>
					</View>
					<Text style={{ fontSize: 14, color: '#61676F', lineHeight: 30, paddingVertical: 10 }}>关联商品</Text>
					<View style={{ flexDirection: 'row', flexWrap: 'wrap', }}>
						{goodsList.map((item, index) => {
							return (
								<TouchableOpacity
									key={index}
									onPress={() => this.deleteGoodsListItem(index)}
									style={{ marginRight: 10 }}
								>
									<Image resizeMode='cover' style={{ width: 88, height: 88, borderWidth: 1, borderColor: '#eee' }} source={{ uri: `${pathHead}${item.goodsMainPic}` }} />
								</TouchableOpacity>
							)
						})}
						{goodsList.length < 9 && (
							<TouchableOpacity
								onPress={() => this.pickGood()}
							>
								<View style={{ backgroundColor: '#fff', width: 88, height: 88, borderWidth: 1, borderColor: '#eee', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }}>
									<Text style={{ fontSize: 40, color: '#fff', lineHeight: 88, }}>+</Text>
								</View>
							</TouchableOpacity>
						)}
					</View>
					<Text style={{ fontSize: 14, color: '#61676F', lineHeight: 30, paddingVertical: 10 }}>上传图片</Text>
					<View style={{ flexDirection: 'row', flexWrap: 'wrap', }}>
						{imageList.map((item, index) => {
							return (
								<TouchableOpacity
									key={index}
									onPress={() => this.deleteImageListItem(index)}
									style={{ marginRight: 10 }}
								>
									<Image resizeMode='cover' style={{ width: 88, height: 88, borderWidth: 1, borderColor: '#eee' }} source={{ uri: `${pathHead}${item}` }} />
								</TouchableOpacity>
							)
						})}
						{imageList.length < 9 && (
							<TouchableOpacity
								onPress={() => this.pickImages()}
							>
								<View style={{ backgroundColor: '#fff', width: 88, height: 88, borderWidth: 1, borderColor: '#eee', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }}>
									<Text style={{ fontSize: 40, color: '#fff', lineHeight: 88, }}>+</Text>
								</View>
							</TouchableOpacity>
						)}
					</View>
				</View>
				<View style={{ padding: 15, backgroundColor: '#fff' }}>
					<TouchableOpacity
						onPress={() => {
							this.hanfleOnPress()
						}}
						style={{
							paddingVertical: 14,
							paddingHorizontal: 20,
							backgroundColor: hotTextColor,
							borderRadius: 6,
							alignItems: 'center',
							justifyContent: 'center',
						}}
					>
						<Text style={{ fontSize: size(28), color: '#fff', lineHeight: size(30), }}>{this.props.children}</Text>
					</TouchableOpacity>
				</View>

				<Modal
					visible={visible}
					transparent={true}
					animationType="slide"
					onRequestClose={() => {
						this.onClose()
						// alert("Modal has been closed.");
					}}
				>
					<View style={{ flex: 1 }}>
						<TouchableOpacity onPress={this.onClose} style={{ flex: 1, backgroundColor: '#000', opacity: .4 }} />
						<View style={{
							height: ScreenHeight - 200,
							flexDirection: 'column',
						}}>

							<CategoriesGoods categoryList={categoryList} select onSelect={this.onSelect} />
						</View>
					</View>
				</Modal>
			</ScrollView>
		);
	}
}

export default connect(({ guestGoodsList, plateList, plateHotList, categoryList }) => ({
	guestGoodsList, plateList, plateHotList, categoryList
}))(CardForm)
